package 我的JDK基础数据结构.BlockingQueue;

import lombok.SneakyThrows;

import java.util.Iterator;

public class Test {

    /**
     * 为何ArrayBlockingQueue一把锁?LinkedBlockingQueue两把锁?
     * 首先两把锁一定比一把锁效率高;
     * 1.ABQ的count使用的是int,而LBQ使用的是AtomicInteger,int型使用两个锁会出现线程安全问题。
     * 2.可能是ABQ如果加双锁就是对同一数组对象进行操作,即多线程处理相同的存储空间,可能会出现线程安全问题。
     */

    @SneakyThrows
    private void testABQ() {
        ArrayBlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<>(4);
        arrayBlockingQueue.offer(1);
        arrayBlockingQueue.offer(2);
        arrayBlockingQueue.offer(3);
        Iterator<Integer> iterator1 = arrayBlockingQueue.iterator();
        arrayBlockingQueue.offer(4);
        Iterator<Integer> iterator2 = arrayBlockingQueue.iterator();

        while (iterator1.hasNext()) {
            System.out.println(iterator1.next());
            System.out.println(iterator2.next());
            arrayBlockingQueue.take();
            arrayBlockingQueue.poll();
        }
        System.out.println("----");
    }

    @SneakyThrows
    private void testLBQ() {
        Test test = new Test();
        test.testABQ();

        LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue(5);
        linkedBlockingQueue.put(1);
        linkedBlockingQueue.put(2);
        linkedBlockingQueue.put(3);
        linkedBlockingQueue.put(4);
        linkedBlockingQueue.put(5);
        Iterator iterator1 = linkedBlockingQueue.iterator();
        Iterator iterator2 = linkedBlockingQueue.iterator();

        while (iterator1.hasNext()) {
            System.out.println(iterator1.next());
            System.out.println(iterator2.next());
            linkedBlockingQueue.poll();
            linkedBlockingQueue.poll();
        }
    }

    public static void main(String[] args) {

    }

}
